package minio.client;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StreamUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import java.io.IOException;
import java.util.Map;

import static java.nio.charset.StandardCharsets.UTF_8;
import static org.springframework.http.ContentDisposition.attachment;
import static org.springframework.http.MediaType.APPLICATION_OCTET_STREAM;
import static org.springframework.http.MediaTypeFactory.getMediaType;

public class MinioWebTemplate extends MinioTemplate {
    public MinioWebTemplate(String bucketName, MinioAsyncClientX minioAsyncClient) {
        super(bucketName, minioAsyncClient);
    }

    public String upload(MultipartFile file) {
        try {
            return upload(file.getOriginalFilename(), file.getContentType(), file.getInputStream(), file.getSize());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public ResponseEntity<StreamingResponseBody> webDownload(String filename) {
        return ResponseEntity.status(HttpStatus.CREATED)
                .contentType(getMediaType(filename).orElse(APPLICATION_OCTET_STREAM))
                .headers(h -> h.setContentDisposition(attachment().filename(filename, UTF_8).build()))
                .body(body -> StreamUtils.copy(download(filename), body));
    }

    public Map<String, Object> createMultipartUpload(String objectName, Integer partTotal) {
        String contentType = getMediaType(objectName).orElse(APPLICATION_OCTET_STREAM).toString();
        return createMultipartUpload(BUCKET_NAME, objectName, contentType, partTotal);
    }
}